--
-- Author: ping.wang
-- Date: 2019-05-28 11:05:33
--
-- RewardWelfareThroughPanel
--

local ClassRef = app.mvc.createPanelClass(...)
local table_insert = table.insert
local string_format = string.format
local string_split = string.split
local TabsBtn = require("app.widget.TabsBtn")
--data =
function ClassRef.createWithData(data, node)
    local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.RewardWelfareThrough))
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init(data)
    return sprite
end
function ClassRef.create(node)
    return ClassRef.createWithData(nil, node)
end

--
function ClassRef:init(data)
    self.super.init(self, data)

    self._isCostEnough = false
    self._topBtns = {}
    local tmpBtn
    for i = 1, 3 do
        tmpBtn = self._ui.Panel:findChild(string_format("btn_%d",i))
        tmpBtn:setEnabled(true)
        table_insert(self._topBtns, tmpBtn)
        tmpBtn:setVisible(false)
    end

    self._selectedIdx = 1
    local function onTabsBtn(index, btn)
        self._selectedIdx = index
        self:_setBtnSelcted(index)
        self:_refreshViewByIndex(index)
    end

    self._tabsBtn = TabsBtn.new(self._topBtns, onTabsBtn, 1)
    self._ui.text:setString(L("levelpromotion5"))
    --配置表 先读进来 按顺序的
    self._costNum = 0
    self._giftPackageId = 9

    self._ui.btn_buy:addClickEventListener(function()
        if self._data and self._data.ids then
            local id = self._data.ids[self._selectedIdx]
            if id then
                local conf = GD:getLevelPromotionDataById(id)
                if conf then
                    --购买的时候需要判断货币是否足够
                    if self._isCostEnough then

                        --此处要求添加一个确定框
                        local confirmBuy = display.newConfirmDialog( string_format(L("levelpromotion11"),self._costNum,conf.level),
                            function() -- 确定
                                executeFunc(self._onOperate,"buyLevelDirect",{activityData = self._data,idx = id})
                            end)
                        UIHandler:addPopDialog( confirmBuy )
                    else
                        if UIHandler:isFunctionOpen(Constant.FUNC_TYPE_SHOP) then
                            local goShopDialog = display.newConfirmDialog( L("levelpromotion7"),
                                function() -- 确定
                                    app:sendMsg("MallController", "buyGameRes", Constant.ShopDraw_ItemId)
                                end)
                            UIHandler:addPopDialog( goShopDialog )
                        else
                            local goShopDialog = display.newConfirmDialog( string_format(L("levelpromotion8"),self._costNum,self._costNum),
                                function() -- 确定
                                    --准备调用支付接口 直接花RMB购买
                                    app:sendMsg("MallModel", "reqBuyGift", {giftID = self._giftPackageId})
                                end)
                            UIHandler:addPopDialog( goShopDialog )
                        end
                    end
                end
            end
        end
    end)

    self._ui.icon_1:addClickEventListener(function()
        if self._data and self._data.ids then
            local id = self._data.ids[self._selectedIdx]
            if id then
                local conf = GD:getLevelPromotionDataById(id)
                if conf then
                    app:sendMsg("RewardController", "openLotteryDropView", GD:getThroughLvDropShow(conf.awardShow))
                else
                    dump("error level through id "..tostring(id))
                end
            end
        end
    end)

    --添加货币
    self._ui.Button_plus:addClickEventListener(function()
        if UIHandler:isFunctionOpen(Constant.FUNC_TYPE_SHOP) then
            app:sendMsg("MallController", "buyGameRes", Constant.ShopDraw_ItemId)
        else
            local goShopDialog = display.newConfirmDialog( string_format(L("levelpromotion8"),self._costNum,self._costNum),
                function() -- 确定
                    --准备调用支付接口 直接花RMB购买

                    app:sendMsg("MallModel", "reqBuyGift", {giftID = self._giftPackageId})
                end)
            UIHandler:addPopDialog( goShopDialog )
        end
    end)

    self._ui.Panel_money:setTouchEnabled(true)
    self._ui.Panel_money:addClickEventListener(handler(self, self._showMoneyTips))

    self:setContentSize( self._ui.Panel:getContentSize() )
end
--根据页数来显示相应的数据
--getLevelPromotionDatas
--data={ids={1,2,3},combatPower = power}
function ClassRef:refresh()
    if self._data and self._data.ids and #self._data.ids > 0 then
        self:setVisible( true )

        local data = self._data
        for i = 1, 3 do
            if data.ids[i] then
                self._topBtns[i]:setVisible(true)
                self:_initBtnContent(self._topBtns[i],GD:getLevelPromotionDataById(data.ids[i]))
            else
                self._topBtns[i]:setVisible(false)
            end
        end

        --每次购买后发送过来的礼包是剩余的 所以从第一个开始
        self._selectedIdx = 1
        self._tabsBtn:setSelected(self._selectedIdx, true)
        self:_refreshViewByIndex(self._selectedIdx)

        self._ui.num:setString(tostring(data.combatPower))
    else
        self:setVisible( false )
    end
end

function ClassRef:refreshViewAfterGetCurrency()
    if self._data and self._data.ids and #self._data.ids > 0 then
        self:_refreshViewByIndex(self._selectedIdx)
    end
end


function ClassRef:_initBtnContent(btn, conf)
    if conf then
        local panel1 = btn:findChild("Panel_1")
        local panel2 = btn:findChild("Panel_2")

        local tlt1 = panel1:findChild("tlt")
        local tlt2 = panel2:findChild("tlt")

        local tips1 = panel1:findChild("tips")
        local tips2 = panel2:findChild("tips")

        tlt1:setString(string_format(L("levelpromotion1"),conf.level))
        tlt2:setString(string_format(L("levelpromotion1"),conf.level))


        --每个panel中有 tlt tips bg2 若已经解锁 需要去掉bg2
        local openDay = app.session:getOpenServerDays()

        if openDay > checknumber(conf.lock) or (openDay == checknumber(conf.lock) and self:isToday()) then
            --解锁
            panel1:findChild("bg2"):setVisible(false)
            panel2:findChild("bg2"):setVisible(false)

            panel1:findChild("tips"):setVisible(false)
            panel2:findChild("tips"):setVisible(false)

            tlt1:setPositionY(37)
            tlt2:setPositionY(37)

            tips1:setVisible(false)
            tips2:setVisible(false)
        else
            --锁住
            tlt1:setPositionY(49)
            tlt2:setPositionY(49)


            panel1:findChild("bg2"):setVisible(true)
            panel2:findChild("bg2"):setVisible(true)

            panel1:findChild("tips"):setVisible(true)
            panel2:findChild("tips"):setVisible(true)

            if (checknumber(conf.lock) - openDay) == 0 then
                tips1:setString(L("levelpromotion10"))
                tips2:setString(L("levelpromotion10"))
            else
                tips1:setString(string_format(L("levelpromotion2"),checknumber(conf.lock) - openDay))
                tips2:setString(string_format(L("levelpromotion2"),checknumber(conf.lock) - openDay))
            end
        end
    end
end


function ClassRef:_setBtnSelcted(idx)
    local panel1,panel2

    for k,v in ipairs(self._topBtns) do
        panel1 = v:findChild("Panel_1")
        panel2 = v:findChild("Panel_2")
        if k == idx then
            panel1:setVisible(true)
            panel2:setVisible(false)
        else
            panel1:setVisible(false)
            panel2:setVisible(true)
        end
    end
end

function ClassRef:_refreshViewByIndex(idx)
    if self._data and self._data.ids then
        local id = self._data.ids[idx]
        if id then
            for i = 1, 3 do
                self._ui.Panel:findChild(string_format("b_num_%d",i)):setVisible(i == id)
                self._ui.Panel:findChild(string_format("s_num_%d",i)):setVisible(i == id)
            end
            local conf = GD:getLevelPromotionDataById(id)
            if conf then
                local openDay = app.session:getOpenServerDays()
                if openDay > checknumber(conf.lock) or (openDay == checknumber(conf.lock) and self:isToday()) then
                    self._ui.btn_buy:setVisible(true)
                    self._ui.Panel_lock:setVisible(false)
                else
                    self._ui.btn_buy:setVisible(false)
                    self._ui.Panel_lock:setVisible(true)
                    if (checknumber(conf.lock) - openDay) == 0 then
                        self._ui.Panel_lock:findChild("text_1"):setString(L("levelpromotion10"))
                    else
                        self._ui.Panel_lock:findChild("text_1"):setString(string_format(L("levelpromotion2"),checknumber(conf.lock) - openDay))
                    end
                end

                self._ui.tips:setString(string_format(L("levelpromotion4"),conf.strength))

                if self._data.combatPower >= tonumber(conf.strength) then
                    self._ui.num:setTextColor(cc.c3b(0,255,0))
                    --同时设置按钮为可点击
                    self._ui.btn_buy:setEnabled(true)
                    display.setBtnGray(self._ui.btn_buy, false)
                else
                    self._ui.num:setTextColor(cc.c3b(255,0,0))
                    --同时设置按钮为不可点击
                    self._ui.btn_buy:setEnabled(false)
                    display.setBtnGray(self._ui.btn_buy, true)
                end

                --价格刷新
                local ary = string_split(conf.sale, "|")
                self._ui.btn_buy:findChild("num_1/num"):setString(ary[3])
                self:initMoneyPanel(tonumber(ary[2]))
                self._isCostEnough = UD:getItemAmountByTid(tonumber(ary[2])) >= tonumber(ary[3])
                self._costNum = tonumber(ary[3])

                if tonumber(conf.ID) == 1 then
                    self._giftPackageId = 7
                elseif tonumber(conf.ID) == 2 then
                    self._giftPackageId = 8
                elseif tonumber(conf.ID) == 3 then
                    self._giftPackageId = 9
                end
            end
        end
    end
end

function ClassRef:onOperate(cb)
    self._onOperate = cb
end


--虽然新添加了货币类型 但是事实上从背包中寻找道具数量
function ClassRef:initMoneyPanel(itemId)
    --新添加的货币 id 以及 道具id
    local coinId = Enums.lootType.starCoin
    local coinConfig = GD:getCoinConfig(coinId)
    local iconPath = string.format("%s%s.png",Res.coinIconPath,coinConfig.icon)
    self._ui.Panel_money:findChild("icon"):loadTexture(iconPath)
    self._ui.Panel_money:findChild("num"):setString(tostring(UD:getItemAmountByTid(itemId)))
end

--显示货币的tips
function ClassRef:_showMoneyTips()
    --local coinId = Enums.lootType.starCoin
    self:showPanelTips(self._ui.Panel_money,{tipsType = Enums.TipsType.item, itemId = Constant.ShopDraw_ItemId})
end

function ClassRef:showPanelTips(panel, param)
    local boundingBoxTemp = panel:getBoundingBox()
    local worldPosTemp = panel:getParent():convertToWorldSpace( cc.p( boundingBoxTemp.x, boundingBoxTemp.y ) )
    boundingBoxTemp.x = worldPosTemp.x
    boundingBoxTemp.y = worldPosTemp.y
    param.boundingBox = boundingBoxTemp
    app:dispatchCustomEvent("EVENT_OPEN_FLOAT", {params = param})
end

--判断服务器发送来的时间是否超过刷新时间点
function ClassRef:isToday()
    local curTime = math.floor(app.session:getServerTime())
    local startHour = tonumber(GD:getSystemPar("daystartsat", 5))
    local tab = os.date("*t", curTime)
    local curHour = tab.hour

    if curHour < startHour then
        -- 刷新时间之前
        return false
    else
        return true
    end
end

return ClassRef
